<?php 

class RealitySynchronizePresenter extends BasePresenter{
	
	/**
	 * Start lifecycle presenter
	 *
	 * @return void
	 */
	protected function startup(){
		
		parent::startup();
		
	}

	/**
	 * Settings for all render
	 *
	 * @return void
	 */
	protected function beforeRender(){

		$this->setLayout("sync");
		
	}

	/**
	 * Render default action
	 *
	 * @return void
	 */
	public function renderDefault($id){
		
		$json_response = null;
		
		
		if(isset($_POST["data"])){
			
			$json = $_POST["data"];
			$json_response = json_decode($json, true);	
			$json_response = $json_response["data"];

				try {

					dibi::query("START TRANSACTION");
					
					$hashes = array();

					foreach($json_response as $reality){
						
						$reality = json_decode($reality, true);
						
						$r = new Reality($reality["name"], $reality["area"], $reality["price"]);
						RealityModel::addReality($r);
						
						$hashes[] = $r->getHash();
					}
					
					dibi::query("COMMIT");
					
					$response = array("status" => "[OK]", "message" => "Bylo synchronizováno " . count($json_response) . " položek.", "hashes" => $hashes);
					$response = json_encode($response, JSON_HEX_QUOT);
					
					$json_response = $response;
				} catch (Exception $e) {
					
					dibi::query("ROLLBACK");
					
					$response = array("status" => "[ERROR]", "message" => "Došlo k chybě při synchronizaci.");
					$response = json_encode($response);
					
					$json_response =  $response;
				}
		}
		
		$this->template->json_response = $json_response;
	}
	
}

?>